package com.campus.controller.user;

import com.campus.constant.JwtClaimsConstant;
import com.campus.pojo.dto.StudentLoginDTO;
import com.campus.pojo.po.Student;
import com.campus.pojo.vo.StudentLoginVO;
import com.campus.properties.JwtProperties;
import com.campus.result.Result;
import com.campus.service.StudentService;
import com.campus.utils.JwtUtil;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequestMapping("/student")
@Tag(name="学生个人")
@RestController
@RequiredArgsConstructor
@Component("userStudentController")
@CrossOrigin
public class StudentController {

    private final JwtProperties jwtProperties;

    private final StudentService studentService;
    @PostMapping("/login")
    public Result login(@RequestBody StudentLoginDTO studentLoginDTO){
        log.info("学生登录：{}", studentLoginDTO);
        //登录
        Student student = studentService.login(studentLoginDTO);
        //map存储Jwt声明
        Map<String, Object> claim = new HashMap<>();
        claim.put(JwtClaimsConstant.ROLE, JwtClaimsConstant.STUDENT);
        claim.put(JwtClaimsConstant.USER_ID, studentLoginDTO.getSno());
        //生成jwt令牌
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claim);

        return Result.success(
                "登录成功",
                StudentLoginVO.builder()
                        .id(student.getId())
                        .sno(student.getSno())
                        .name(student.getName())
                        .token(token)
                        .build()
        );
    }
}
